<template>
  <div class="login-box">
    <!-- login box -->
    <div class="login-box-box">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm">
        <!-- // 账号 -->
        <el-form-item prop="userId">
          <template #label>
            <el-icon style="font-size: 20px; font-weight: 700;">
              <User />
            </el-icon>
          </template>
          <el-input v-model="ruleForm.userId" autocomplete="off" placeholder="请输入账号" clearable />
        </el-form-item>
        <!-- // 密码 -->
        <el-form-item prop="password">
          <template #label>
            <el-icon style="font-size: 20px; font-weight: 700;">
              <Lock />
            </el-icon>
          </template>
          <el-input v-model="ruleForm.password" type="password" autocomplete="off" placeholder="请输入密码" show-password
            clearable />
        </el-form-item>
        <!-- // 验证码 -->
        <el-form-item prop="captcha">
          <template #label>
            <el-icon style="font-size: 20px; font-weight: 700;">
              <Key />
            </el-icon>
          </template>
          <el-input v-model="ruleForm.captcha" placeholder="请输入验证码" clearable>
            <template #append>
              <div class="captcha clearfix" @click="handleCaptchaClick">
                <div class="img" v-html="imgPath"></div>
              </div>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="btns">
      <el-button type="primary" size="large" @click="submitForm(ruleFormRef)" style="font-weight: 700;">登录</el-button>
      <el-button size="large" link class="reg-btn" @click="loginOrRegFunc" style="font-weight: 700;">
        去注册
        <el-icon>
          <ArrowRight />
        </el-icon>
      </el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, onMounted } from "vue"
import type { FormInstance, FormRules } from 'element-plus'
import {
  User,
  Lock,
  Key,
  ArrowRight,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from "element-plus";
import "element-plus/es/components/message/style/css"; // 按需引入ElMessage样式失败，手动引入
import "element-plus/es/components/message-box/style/css";
import { useRoute, useRouter } from 'vue-router'
import Service from '@/utils/axios'
//pinia
import { useUserStore } from "@/store/user";
const userStore = useUserStore();

const route = useRoute()
const router = useRouter()

// 请求到的验证码path
const imgPath = ref<any>()

const ruleFormRef = ref<FormInstance>()

// 表单验证正则表达式
const userIdRegex = /^[A-Za-z0-9]{5,17}$/;
const passwordIdRegex = /^[a-zA-Z]\w{3,16}$/;


const checkUserId = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入账号'))
  } else if (!userIdRegex.test(value)) {
    callback(new Error('请输入长度为4-17,由字母和数字组成的账号'))
  } else {
    callback()
  }
}

const checkPassword = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (!passwordIdRegex.test(value)) {
    callback(new Error('请输入长度为5-17,由字母开头，字母和数字组成的密码'))
  } else {
    callback()
  }
}
const checkCaptcha = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入验证码'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  userId: '',
  password: '',
  captcha: '',
})

const rules = reactive({
  userId: [{ validator: checkUserId, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }],
  captcha: [{ validator: checkCaptcha, trigger: 'blur' }],
})

// 图形验证码点击事件-刷新验证码
const handleCaptchaClick = () => {
  getCaptchaFunc();
}

// 提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('提交成功!')
      const form = {
        username: ruleForm.userId,
        password: ruleForm.password,
        captcha: ruleForm.captcha,
      }
      Service.post('/bkapi/api/loginUser', form)
        .then((res: any) => {
          // console.log('res.data.status', res.data)
          if (res.data.status === 200) {
            // 登录成功
            userStore.setToken(res.data.token);
            userStore.setUserName(ruleForm.userId);
            Service.get('/bkapi/userinfo/getUserinfoByUsername', {
              params: {
                username: ruleForm.userId,
              }
            }).then((res2: any) => {
              if (res2.data.status === 200) {
                userStore.setAvatarUrl(res2.data.data.user_pic);
                userStore.setUserInfo(JSON.stringify(res2.data.data));
                userStore.setUserId(res2.data.data.user_id)
                // 登录成功，获取当前用户信息
                ElMessage({
                  showClose: true,
                  message: '登录成功',
                  type: 'success',
                })
                router.go(1);
                router.push({
                  name: 'Index',
                });
              } else {
                // 登录成功,但未成功获取当前用户信息
                ElMessage({
                  showClose: true,
                  message: '服务器内部错误',
                  type: 'error',
                })
              }
            })
          } else {
            // 登录失败
            ElMessage({
              showClose: true,
              message: `${res.data.message}`,
              type: 'error',
            })
          }
        })
    } else {
      console.log('提交失败!')
      return false
    }
  })
}

// 清空表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 定义切换登录注册事件
const emit = defineEmits(['loginOrReg'])
// 触发切换登录注册事件的方法
const loginOrRegFunc = () => {
  console.log('切换登录注册')
  emit('loginOrReg', 1)
}


const getCaptchaFunc = async () => {
  await Service.get('/bkapi/captcha')
    .then((res: any) => {
      imgPath.value = res.data;
    });
}

onMounted(() => {
  getCaptchaFunc()
})
</script>

<style lang="less" scoped>
@border-color: #dcdfe6; //边框默认颜色

.login-box {

  &-box {
    width: 450px;
    padding-top: 30px;
    padding-right: 100px;

    :deep(.el-form-item__label) {
      align-items: center;
    }

    .captcha {
      width: 120px;
      height: 30px;
      position: relative;

      .img {
        border: 1px solid @border-color;
        height: 60px;
        position: absolute;
        top: -50%;
      }
    }

    :deep(.el-input-group__append) {
      padding: 0;
    }
  }

  .btns {
    width: 100%;
    padding-top: 20px;
    display: flex;
    justify-content: center;
    position: relative;

    :deep(.el-button--large) {
      padding: 12px 40px;
      font-size: 17px;
    }

    :deep(.el-button--large):first-child {
      padding: 12px 80px;
    }


    .reg-btn {
      position: absolute;
      right: 60px;
    }
  }
}
</style>